import {Component} from '@angular/core';
import {TranslateService} from '@ngx-translate/core';
import {IonicPage, NavController, Loading} from 'ionic-angular';
import {User, Prompt, CacheService,CacheKeys} from '../../../providers';
import {MainPage} from '../../';
import md5 from 'js-md5'

/**
 * @description 登录页面数据处理
 * @author 李元坝
 * @date 20180611
 */

@IonicPage()
@Component({
  selector: 'page-login',
  templateUrl: 'login.html'
})
export class LoginPage {

  account: { mobile: string, password: string };

  // Our translated text strings
  private loginErrorString: string;

  constructor(public navCtrl: NavController,
              public user: User,
              private cacheService: CacheService,
              public translateService: TranslateService,
              private prompt: Prompt) {

    this.translateService.get('LOGIN_ERROR').subscribe((value) => {
      this.loginErrorString = value;
    });

    this.account = {
      mobile: user._account,
      password: ''
    };
  }

  /**
   * 用户登录方法
   * @author 李元坝
   * @date 2018-06-06
   * @returns {boolean}
   */
  doLogin() {
    if (this.account.mobile == null || this.account.mobile == "") {
      this.prompt.showToast('账号不能为空', 'bottom', 1000);
      return false;
    }
    if (this.account.password == null || this.account.password == "") {
      this.prompt.showToast('密码不能为空', 'bottom', 1000);
      return false;
    }
    this.account.password = md5(this.account.password);//MD5加密

    let loading: Loading = this.prompt.createCommonLoading('正在登录');
    loading.present();

    this.user.login(this.account).subscribe((resp: any) => {
      loading.dismiss();

      if (resp.user == null) {
        this.prompt.showToast('手机号或密码不正确', 'bottom', 1000);
        return false;
      }
      // 存储用户信息
      this.cacheService.set(CacheKeys.User, resp).catch();

      this.navCtrl.push(MainPage);
    }, (err) => {
      loading.dismiss();
      this.prompt.showToast(this.loginErrorString);
    });
  }
}
